<!--
 * @Author: chunlai
 * @Date: 2023-07-26 10:33:07
 * @LastEditTime: 2025-09-05 08:39:45
 * @LastEditors: minsheng_insurance_agency_zhoucl
 * @FilePath: \02.bldinsure\src\views\form\index.vue
 * @Description: 客户信息录入
-->
<template>
  <div class="form_page">
    <Applicant
      ref="appliRef"
      :class="{ disabledForm: disabledEdit }"
    ></Applicant>
    <div
      :class="slPreWarn || disabledEdit ? 'disabledForm' : ''"
      @click="noAuthHandle"
    >
      <MultiAssured
        ref="assuredRef"
        v-if="bbrMinNum > 0 && bbrRefresh"
      ></MultiAssured>
      <Count ref="coundRef"></Count>
    </div>
    <RenewalModal
      ref="renewalRef"
      :class="insu3Status == '3' ? 'disabledForm' : ''"
      v-if="renewalShowModal"
    ></RenewalModal>
    <div style="padding: 20px 0 80px">
      <van-divider>用心服务每一位</van-divider>
    </div>
    <FooterBtns
      rightText="下一步"
      @saveField="clickEvent('temp')"
      @saveForm="clickEvent('save')"
    ></FooterBtns>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import Applicant from "./components/Applicant";
import MultiAssured from "./components/MultiAssured";
import Count from "./components/Count";
import RenewalModal from "./components/RenewalModal";
import { paymentAuthApply } from "@/utils/functions";
import { rebackUrlPath } from "@/methods/format.js";
import { pagesMixin } from "@/mixins/pages";
export default {
  name: "InsureInfoMainPage",
  components: {
    Applicant,
    MultiAssured,
    Count,
    RenewalModal,
  },
  data() {
    return {
      userApi: null,
    };
  },
  computed: {
    ...mapGetters({
      appnt: "insert/appnt",
      apiBbrMult: "insert/apiBbrMult",
      renewalInfo: "insert/renewalInfo",
      bbrRefresh: "common/bbrRefresh",
      slPreWarn: "common/slPreWarn",
      insu3Status: "json/insu3Status",
      renewal: "page/renewal",
      preNotice: "page/preNotice",
      bbrMinNum: "page/bbrMinNum",
      noticeConfigType: "page/noticeConfigType",
      showedRisks: "risks/showedRisks",
    }),
    renewalShowModal() {
      let res = false;
      if (Object.keys(this.renewal).length > 0) {
        if (["1", "3"].includes(this.isNetInsure)) {
          res = true;
        }
        if (this.compEngName == "bainian") {
          const isHas = this.showedRisks.filter((ele) => ele.payendyear == "1");
          if (isHas && isHas.length > 0) {
            res = true;
          }
        }
      }
      return res;
    },
  },
  mixins: [pagesMixin],
  created() {},
  mounted() {
    this.$nextTick(() => {
      window.scrollTo(0, 0);
    });
  },
  methods: {
    noAuthHandle() {
      if (this.slPreWarn) {
        this.$store.commit("common/SET_FIELD_MEAN_CONT", {
          label: `双录提示`,
          desc: `根据地区监管规定,此投保申请须双录（同步进行录音、录像）,请联系业务员使用《WE易保》投保和双录。`,
        });
      }
    },
    clickEvent(source = "temp") {
      if (this.disabledEdit) {
        if (this.insu3Status == "1") {
          return this.updateXuBaoBank();
        }
        return this.forbidChange();
      }
      if (this.slPreWarn) {
        return this.noAuthHandle();
      }
      this.userApi = null;
      if (!this.appnt.name) return this.$toast("请输入投保人姓名");
      if (!this.appnt.idNum) return this.$toast("请输入投保人证件号");
      /**高级错误校验*/
      // 1.被保人关系校验
      const selfNum = this.apiBbrMult.filter((e) => e.relationToAppnt == "4");
      if (selfNum.length > 1) {
        this.$msAlert("被保险人最多只能有一个同投保人，请确认");
        return;
      }
      // 2.百年续保重置
      if (!this.renewalShowModal && this.compEngName == "bainian") {
        this.$store.commit("insert/UPDATE_RENEWAL_INFO", {
          renewFlag: "-2",
        });
      }
      /**保存*/
      this.$store
        .dispatch("apis/userSaveApi", this.apiComParams)
        .then((data) => {
          if (data.code == "1") {
            this.userApi = data;
            this.$store
              .dispatch("apis/riskSaveApi", this.apiComParams)
              .then((res) => {
                if (res.code == "1") {
                  this.$setMessage("saveOrder", "1");
                  this.setWxShareConfig(this.$route);
                  this.nextValidStep(source);
                } else {
                  this.$msAlert(res.msg);
                }
              });
          } else {
            this.$msAlert(data.msg);
          }
        });
    },
    async nextValidStep(source) {
      if (source === "temp") return;
      // 1.校验投保人信息
      let breakTips = [];
      let flag1 = await this.$refs.appliRef.saveForm();
      if (!flag1.status) return;
      breakTips = breakTips.concat(flag1.breakTips);
      // 2.校验被保人信息
      if (this.bbrMinNum > 0) {
        let flag2 = await this.$refs.assuredRef.saveForm();
        if (!flag2.status) return;
        breakTips = breakTips.concat(flag2.breakTips);
      }
      // 4.校验保单信息
      let flag4 = await this.$refs.coundRef.saveForm();
      if (!flag4.status) return;
      breakTips = breakTips.concat(flag4.breakTips);
      // 3.校验续保信息
      if (this.renewalShowModal) {
        let flag3 = await this.$refs.renewalRef.saveForm();
        if (!flag3.status) return;
        breakTips = breakTips.concat(flag3.breakTips);
      }
      /**非阻断提示*/
      breakTips = breakTips.filter((b) => b);
      // console.log("api---", breakTips);
      if (breakTips.length > 0) {
        this.$baseConfirm(
          breakTips.join(";"),
          () => {
            this.saveBeforeApi();
          },
          null,
          "继续投保",
          "修改信息"
        );
      } else {
        this.saveBeforeApi();
      }
    },
    saveBeforeApi() {
      this.$store
        .dispatch("insert/validateInsureRule")
        .then((res) => {
          //a.计算费率
          this.$store.dispatch("risks/setRisks", {}).then(() => {
            //b.保存信息
            this.userApiValid();
          });
        })
        .catch((err) => {
          this.$msAlert(err);
        });
    },
    userApiValid() {
      if (this.isNetInsure == "1" && this.userApi) {
        // 1不需要签约 0需要签约
        if (this.userApi.bankNeedSign == "1") {
          this.toHeBaoHandle();
        } else {
          this.payAuthApplyApi();
        }
      } else {
        // 保存险种信息
        this.$store
          .dispatch("apis/riskSaveApi", this.apiComParams)
          .then((res) => {
            if (res.code == "1") {
              this.routerPath();
            } else {
              this.$msAlert(res.msg);
            }
          });
      }
    },
    payAuthApplyApi() {
      this.$store.commit("updateLoad", true);
      let params = {
        ...this.apiComParams,
        signType: "01",
        successUrl: `${rebackUrlPath(`#/form?signres=1`)}`,
        failUrl: `${rebackUrlPath(`#/form?signres=2`)}`,
      };
      paymentAuthApply(params).then(
        ({ data }) => {
          this.$store.commit("updateLoad", false);
          this.handleCode(data);
        },
        (err) => {
          this.$store.commit("updateLoad", false);
        }
      );
    },
    handleCode(apiRes) {
      if (apiRes.code === "3") {
        this.$baseAlert(apiRes.msg, () => {
          this.toHeBaoHandle();
        });
      } else if (["0", "6"].includes(apiRes.code)) {
        this.$msAlert(`${apiRes.msg || "签约失败"}，可更换银行卡重新签约`);
      } else {
        this.$baseConfirm(
          `${apiRes.msg}`,
          () => {
            if (apiRes.url) {
              window.location.href = apiRes.url;
            }
          },
          () => {},
          `去签约`
        );
      }
    },
    toHeBaoHandle() {
      this.$router.push("/billsure");
    },
    routerPath() {
      // 去除现价表阅读
      sessionStorage.removeItem("is_read_cash");
      if (this.preNotice || this.noticeConfigType === "1") {
        return this.$router.push("/files"); // 前置告知
      }
      // 安盛
      if (this.isNetInsure == "3") {
        return this.$router.push("/billsure");
      }
      this.$router.push("/healthy");
    },
    updateXuBaoBank() {
      this.$store
        .dispatch("apis/comAdminApiRequest", {
          apiParams: {
            ...this.apiComParams,
            cont: this.renewalInfo,
          },
          apiName: "modifyBankInfo",
          toast: true,
        })
        .then((data) => {
          if (data.code == "1") {
            this.$router.push("/billsure");
          }
        });
    },
  },
};
</script>

<style lang="less" scoped></style>
